package resdao

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"xr-game-server/core/cache"
	"xr-game-server/core/constants/common"

	"xr-game-server/entity"
)

var resCache *cache.CacheMgr

// GetResBy 根据玩家id拉取数据
func GetResBy(roleId uint64) []*entity.PlayerRes {
	//命中不了缓存，从数据库拉取数据
	cacheData := resCache.GetData(roleId, func(ctx context.Context) (value interface{}, err error) {
		//从数据库拉取数据
		res := make([]*entity.PlayerRes, common.Zero)
		err = g.Model(string(entity.TbPlayerRes)).Unscoped().Where(string(entity.PlayerResRoleId), roleId).Scan(&res)
		return res, nil
	})
	return cacheData.([]*entity.PlayerRes)
}

func GetOneRes(roleId uint64, typeId uint64) *entity.PlayerRes {
	cacheData := GetResBy(roleId)
	for _, res := range cacheData {
		if res.TypeId == typeId {
			return res
		}
	}
	return nil
}

func AddRes(res *entity.PlayerRes) {
	resCacheData := GetResBy(res.RoleId)
	newRes := append(resCacheData, res)
	resCache.FlushCache(res.RoleId, newRes)
}

func InitResDao() {
	resCache = cache.NewCacheMgr()
}
